package net.suncaper.mvc.web.controller;

import net.suncaper.mvc.common.framework.simplemvc.RequestMapping;
import net.suncaper.mvc.common.utils.JSONUtil;
import net.suncaper.mvc.common.utils.Result;
import net.suncaper.mvc.model.domain.Order;
import net.suncaper.mvc.model.vo.OrderVO;
import net.suncaper.mvc.common.utils.EntityConverter;
import net.suncaper.mvc.service.IOrderService;
import net.suncaper.mvc.service.impl.OrderServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 订单控制层
 */
@RequestMapping("/api/order")
public class OrderController {
    private final IOrderService orderService = new OrderServiceImpl();

    /**
     * 创建订单
     * 请求参数：userId（用户ID）、hotelName（酒店名称）、roomType（房型）
     */
    @RequestMapping("/create.do")
    public void createOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取请求参数
            String userId = request.getParameter("userId");
            String hotelName = request.getParameter("hotelName");
            String roomType = request.getParameter("roomType");

//            // 打印room对象的所有属性（关键排查代码）
//            System.out.println("===== 房间信息打印 =====");
//            System.out.println("roomType: " + roomType);
//            System.out.println("hotelName: " + hotelName);

            // 调用业务层创建订单
            Order order = orderService.createOrder(userId, hotelName, roomType);

            // 返回创建成功的订单信息（包含自增ID）
            if (order != null) {
                OrderVO orderVO = EntityConverter.convertToOrderVO(order);
                JSONUtil.printByJSON(response, Result.success(orderVO));
            } else {
                JSONUtil.printByJSON(response, Result.error("订单创建失败"));
            }
        } catch (Exception e) {
            // 捕获业务异常并返回错误信息
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 支付订单
     * 请求参数：orderId（订单ID）、paymentMethod（支付方式）、amount（支付金额）
     */
    @RequestMapping("/pay.do")
    public void payOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取请求参数
            String orderId = request.getParameter("orderId");
            String paymentMethod = request.getParameter("paymentMethod");
            BigDecimal amount = new BigDecimal(request.getParameter("amount"));

            // 调用业务层支付订单
            orderService.payOrder(orderId, paymentMethod, amount);

            // 返回支付成功标识
            JSONUtil.printByJSON(response, Result.success("支付成功"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 取消订单
     * 请求参数：orderId（订单ID）
     */
    @RequestMapping("/cancel.do")
    public void cancelOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取请求参数
            String orderId = request.getParameter("orderId");

            // 调用业务层取消订单
            orderService.cancelOrder(orderId);

            // 返回取消成功标识
            JSONUtil.printByJSON(response, Result.success("取消成功"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 获取用户所有订单
     * 请求参数：userId（用户ID）
     */
    @RequestMapping("/user/list.do")
    public void getUserOrders(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String userId = request.getParameter("userId");
            List<Order> orders = orderService.getUserOrders(userId);
            if (orders != null && !orders.isEmpty()) {
                java.util.List<OrderVO> orderVOList = EntityConverter.convertToOrderVOList(orders);
                JSONUtil.printByJSON(response, Result.success(orderVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("用户暂无订单"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 获取所有订单（管理员功能）
     */
    @RequestMapping("/all/list.do")
    public void getAllOrders(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            List<Order> orders = orderService.getAllOrders();
            if (orders != null && !orders.isEmpty()) {
                java.util.List<OrderVO> orderVOList = EntityConverter.convertToOrderVOList(orders);
                JSONUtil.printByJSON(response, Result.success(orderVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("暂无订单信息"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据酒店名称获取订单
     * 请求参数：hotelName（酒店名称）
     */
    @RequestMapping("/hotel/list.do")
    public void getOrdersByHotel(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String hotelName = request.getParameter("hotelName");
            List<Order> orders = orderService.getOrdersByHotel(hotelName);
            if (orders != null && !orders.isEmpty()) {
                java.util.List<OrderVO> orderVOList = EntityConverter.convertToOrderVOList(orders);
                JSONUtil.printByJSON(response, Result.success(orderVOList));
            } else {
                JSONUtil.printByJSON(response, Result.error("该酒店暂无订单"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据订单ID查询订单
     * 请求参数：id（订单号）
     */
    @RequestMapping("/get.do")
    public void getOrderById(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String idStr = request.getParameter("id");
            if (idStr == null) {
                JSONUtil.printByJSON(response, Result.error("订单号不能为空"));
                return;
            }
            Order order = orderService.getOrderById(idStr);
            if (order != null) {
                OrderVO orderVO = EntityConverter.convertToOrderVO(order);
                JSONUtil.printByJSON(response, Result.success(orderVO));
            } else {
                JSONUtil.printByJSON(response, Result.error("订单不存在"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 更新订单信息
     * 请求参数：id（订单号）、amount、paymentMethod、payTime、cancelTime
     */
    @RequestMapping("/update.do")
    public void updateOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String idStr = request.getParameter("id");
            if (idStr == null) {
                JSONUtil.printByJSON(response, Result.error("订单号不能为空"));
                return;
            }
            int id = Integer.parseInt(idStr);
            String amountStr = request.getParameter("amount");
            String paymentMethod = request.getParameter("paymentMethod");
            String payTime = request.getParameter("payTime");
            String cancelTime = request.getParameter("cancelTime");
            Order order = new Order();
            order.setId(id);
            if (amountStr != null && !amountStr.isEmpty()) {
                order.setAmount(new java.math.BigDecimal(amountStr));
            }
            if (paymentMethod != null && !paymentMethod.isEmpty()) {
                order.setPaymentMethod(paymentMethod);
            }
            if (payTime != null && !payTime.isEmpty()) {
                order.setPayTime(java.sql.Timestamp.valueOf(payTime));
            }
            if (cancelTime != null && !cancelTime.isEmpty()) {
                order.setCancelTime(java.sql.Timestamp.valueOf(cancelTime));
            }
            boolean result = orderService.updateOrder(order);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 删除订单
     * 请求参数：id（订单号）
     */
    @RequestMapping("/delete.do")
    public void deleteOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String idStr = request.getParameter("id");
            if (idStr == null) {
                JSONUtil.printByJSON(response, Result.error("订单号不能为空"));
                return;
            }
            boolean result = orderService.deleteOrder(idStr);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
}